#include "Reader.h"

/*
 *--------------------------------------------------------------------------------------
 *       Class:  Reader
 *      Method:  Reader
 * Description:  Constrói um leitor de arquivo passando o nome, o offset e o tamanho do
 *               bloco que será lido
 *--------------------------------------------------------------------------------------
 */
Reader::Reader(char *filename, ulong offset, ulong blockSize)
{
    this->blockSize = blockSize;

    instream.open(filename);
    assert(instream.is_open());
    instream.seekg(offset);
}

Reader::~Reader()
{
    instream.close();
}

/*
 *--------------------------------------------------------------------------------------
 *       Class:  Reader
 *      Method:  readBlock
 * Description:  Lê um bloco do arquivo
 *--------------------------------------------------------------------------------------
 */
string * Reader::readBlock()
{
    char buffer[blockSize + 1];

    /* Lê BLOCK_SIZE chars do arquivo */
    instream.read(&buffer[0], sizeof(char) * blockSize);
    string *str = new string(buffer, instream.gcount());

    return str;
}

/*
 *--------------------------------------------------------------------------------------
 *       Class:  Reader
 *      Method:  fileExists
 * Description:  Verifica se o arquivo existe
 *--------------------------------------------------------------------------------------
 */
bool Reader::fileExists(char *filename)
{
    ifstream in(filename);
    bool exists = in.is_open();
    in.close();
    return exists;
}

/*
 *--------------------------------------------------------------------------------------
 *       Class:  Reader
 *      Method:  getLength
 * Description:  Retorna o tamanho do arquivo
 *--------------------------------------------------------------------------------------
 */
ulong Reader::getLength(char *filename)
{
    ifstream in(filename);
    in.seekg(0, ios::end);
    ulong length = in.tellg();
    in.close();
    return length;
}
